<?php

namespace app\api\controller;

use ba\Tree;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Frontend;
use app\common\library\token\TokenExpirationException;

use app\api\model\Nav;
use app\api\model\Category;
use app\api\model\Tags;
use app\api\model\Activity;
use app\api\model\Times;
use app\api\model\AdszoneAds;



class Index extends Frontend
{
    protected array $noNeedLogin = ['index','banner','nav','activity','times','category'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 前台和会员中心的初始化请求
     * @throws Throwable
     */
    public function index(): void
    {
        $menus = [];
        if ($this->auth->isLogin()) {
            $rules     = [];
            $userMenus = $this->auth->getMenus();

            // 首页加载的规则，验权，但过滤掉会员中心菜单
            foreach ($userMenus as $item) {
                if ($item['type'] == 'menu_dir') {
                    $menus[] = $item;
                } elseif ($item['type'] != 'menu') {
                    $rules[] = $item;
                }
            }
            $rules = array_values($rules);
        } else {
            // 若是从前台会员中心内发出的请求，要求必须登录，否则会员中心异常
            $requiredLogin = $this->request->get('requiredLogin/b', false);
            if ($requiredLogin) {

                // 触发可能的 token 过期异常
                try {
                    $token = get_auth_token(['ba', 'user', 'token']);
                    $this->auth->init($token);
                } catch (TokenExpirationException) {
                    $this->error(__('Token expiration'), [], 409);
                }

                $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }

            $rules = Db::name('user_rule')
                ->where('status', 1)
                ->where('no_login_valid', 1)
                ->where('type', 'in', ['route', 'nav', 'button'])
                ->order('weigh', 'desc')
                ->select()
                ->toArray();
            $rules = Tree::instance()->assembleChild($rules);
        }

        $this->success('', [
            'site'             => [
                'siteName'     => get_sys_config('site_name'),
                'version'      => get_sys_config('version'),
                'cdnUrl'       => full_url(),
                'upload'       => keys_to_camel_case(get_upload_config(), ['max_size', 'save_name', 'allowed_suffixes', 'allowed_mime_types']),
                'recordNumber' => get_sys_config('record_number'),
                'cdnUrlParams' => Config::get('buildadmin.cdn_url_params'),
            ],
            'openMemberCenter' => Config::get('buildadmin.open_member_center'),
            'userInfo'         => $this->auth->getUserInfo(),
            'rules'            => $rules,
            'menus'            => $menus,
        ]);
    }

    public function banner(): void
    {
        $banners = AdszoneAds::where('zone_id', 1)->order('weigh', 'desc')->select()->toArray();
        $this->success('', $banners);
    }

    /**
     * 导航菜单
     */
    public function nav(): void
    {
        $navs = Nav::where('status', 1)->order('weigh', 'desc')->field('id,nav_name as title,image,weigh,url,type,is_login')->select()->toArray();
        $this->success('', $navs);
    }

    /**
     * 活动分类
     */
    public function category(): void
    {
        $categories = Category::where('status', 1)->order('weigh', 'desc')->field('`id` as `category_id`,`cate_name` as `title`, `id`*0 as `follow`,`id`*0 as `is_login`')->select()->toArray();
        $this->success('', $categories);
    }

    /**
     * 活动列表
     */
    public function activity(): void
    {
        $map[] = ['times.status','=', 1];
        $map[] = ['times.activity_times','between', [strtotime(date('Y-m-d')), mktime(0, 0, 0, date("m"), date("d") + 8, date("Y"))]];
        $activities = Times::withJoin('activity')->order('times.activity_times', 'desc')->where($map)->select()->toArray();
        $this->success('', $activities);
    }

    /**
     * 活动时间
     */
    public function times(): void
    {
        
            $page = $this->request->post('page/d', 1);
            $category_id = $this->request->post('category_id/d', 0);
            $follow = $this->request->post('follow/d', 0);
            $map[] = ['times.status','=', 1];
            if($category_id >0){
                $map[] =['activity.cate_id','=',$category_id] ;
            }
            if($follow > 0){
                $follows = $this->auth->getActivityFollows();
                $map[] = ['times.special_activity_id','in', $follows];
            }
            $times = Times::withJoin('activity')->order('activity_times', 'desc')->where($map)->page($page,10)->select()->toArray();
            $this->success('', $times);
        
    }
    
}